<?php

namespace App\Http\Controllers\Admin;

use App\Model\SliderModel;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class SliderController extends CommonController
{
    //
    public function index(){
      $data = SliderModel::all();
      return view("admin.slider.index")->with('list',$data);
    }

    public function show(){

    }

    public function create(){

        return view('admin.slider.slider_add');
    }

    public function store(){
      $input = Input::except("_token");
        $rules = array(
            's_title'=>'required',
           // 'img_src'=>'required|mimes:jpeg,bmp,png,jpg'
        );
        $message = array(
            'art_title.required'=>'标题不能为空!'
            ,'img_src.required'=>'图片比传!',
           // 'img_src.mimes'=>'上传的文件必须是图片'
        );
        $validator = Validator::make($input,$rules,$message);

        if($validator->passes()){
            $add = SliderModel::create($input);
            if($add){
               return redirect("Admin/slider");
           }else{
                return back()->with('errors','上传失败');
            }
        }else{
            return back()->withErrors($validator);
        }
    }

    public function edit($id){
        $data = SliderModel::find($id);
        return view("admin.slider.slider_edit")->with('data',$data);
    }

    public function update($id){
        $all = Input::except('_token','_method','img_src');
        $img = Input::all()['img_src'];
        $oldImg = SliderModel::find($id)->img_src;
        if($img && $img!=''){
          if(is_file($oldImg)) unlink($oldImg);
          $all['img_src'] = $img;
        }


        $rules = array(
            's_title'=>'required',
            // 'img_src'=>'required|mimes:jpeg,bmp,png,jpg'
        );
        $message = array(
            'art_title.required'=>'标题不能为空!'
            // 'img_src.mimes'=>'上传的文件必须是图片'
        );
        $validator = Validator::make($all,$rules,$message);

        if($validator->passes()){
            $add = SliderModel::where('s_id',$id)->update($all);
            if($add){
                return redirect("Admin/slider");
            }else{
                return back()->with('errors','修改失败');
            }
        }else{
            return back()->withErrors($validator);
        }

    }

    public function destroy($id){
        $image =  SliderModel::select('img_src')->find($id)->img_src;
        if (is_file($image)) unlink($image);
        $del =  SliderModel::where('s_id',$id)->delete();
        $data = array(
            'code'=>0,
            'msg' =>'删除成功'
        );
        if(!$del){
            $data['code'] = 1001;
            $data['msg'] = "删除失败";
        }
        return $data;
    }
}
